package com.pengweiwei.androidzygote.functions.csutomviews;

import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.putong35.common.customviews.ImageViewPager;


/**
 * Simple to Introduction
 *
 * @Author: PengWeiwei
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017-04-10
 * @Version: 1.0.0
 * @Description viewpager自动滚动，滑动到最后一页之后，跳到第一页
 */
public class ViewPagerAutomator {

    private long intervalInMills = 1000;
    private ImageViewPager mViewPager;
    private SmartTabLayout mIndicator;


    public static final int MSG_TICK = 0X01;
    public static final int MSG_START = 0X02;
    public static final int MSG_STOP = 0X03;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_TICK:
                    // next page
                    int pageCount = mViewPager.getChildCount();
                    int nextPage = (mViewPager.getCurrentItem() + 1) % pageCount;
                    mViewPager.setCurrentItem(nextPage, true);
                    mHandler.sendEmptyMessageDelayed(MSG_TICK, intervalInMills);
                    break;

                case MSG_START:
                    break;

                case MSG_STOP:
                    break;
            }

        }
    };

    public ViewPagerAutomator(ImageViewPager vpAutoSwitch, SmartTabLayout indicatorOfAutoSwitchVP) {
        mViewPager = vpAutoSwitch;
        mIndicator = indicatorOfAutoSwitchVP;
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        stop();
                        break;

                    case MotionEvent.ACTION_UP:
                        start();
                        break;

                }
                return false;
            }
        });
    }

    public void start() {
        stop();
        mHandler.sendEmptyMessageDelayed(MSG_TICK, intervalInMills);
    }

    public void stop() {
        mHandler.removeMessages(MSG_TICK);
        mHandler.removeMessages(MSG_START);
    }

    public void setInterval(long intervalInMills) {
        this.intervalInMills = intervalInMills;
    }



}
